﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace Kugar.Core.WinForm
{
    public class WaitNotBlockUI
    {
        private bool IsLock = true;
        private int _waitTime = 0;
        private Stopwatch watch = new Stopwatch();
        private bool _isSuccess = false;


        public void Unlock()
        {
            _isSuccess = true;
            IsLock = false;
            watch.Stop();
        }

        public bool Lock(int waitTime)
        {
            _isSuccess = false;
            _waitTime = waitTime;

            if (_waitTime > 0)
            {
                watch.Reset();
                watch.Start();
            }

            while (IsLock)
            {
                try
                {
                    Application.DoEvents();

                    if (watch.IsRunning && _waitTime>0 && watch.ElapsedMilliseconds > _waitTime)
                    {
                        IsLock = false;
                        watch.Stop();
                        break;
                    }
                }
                catch (Exception)
                {
                    Thread.Sleep(500);
                    continue;
                }

            }

            return _isSuccess;

        }

        public bool Lock()
        {
            return Lock(-1);
        }

        public static void Wait(int waitTime)
        {
            var watch = new Stopwatch();


            if (waitTime > 0)
            {
                watch.Reset();
                watch.Start();
            }

            while (true)
            {
                try
                {
                    Application.DoEvents();

                    if (watch.IsRunning && watch.ElapsedMilliseconds > waitTime)
                    {
                        //IsLock = false;
                        watch.Stop();
                        break;
                    }
                }
                catch (Exception)
                {
                    Thread.Sleep(500);
                    continue;
                }
            }
        }
    }


}
